package com.zone.gateway.core.executor;

import com.zone.gateway.core.datasource.Connection;
import com.zone.gateway.core.mapping.HttpStatement;
import com.zone.gateway.core.session.Configuration;
import com.zone.gateway.core.type.SimpleTypeRegister;
import com.zone.gateway.core.executor.result.SessionResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author: zongzi
 * @description: 基础执行器，统一执行流程
 * @date: 2025/4/22
 */
public abstract class BaseExecutor implements Executor {
    private final Logger logger = LoggerFactory.getLogger(BaseExecutor.class);

    protected Configuration configuration;
    protected Connection connection;

    public BaseExecutor(Configuration configuration, Connection connection) {
        this.configuration = configuration;
        this.connection = connection;
    }

    @Override
    public SessionResult execute(HttpStatement httpStatement, Map<String, Object> args) {
        // todo 目前rpc限制入参为单个
        // 参数类型
        String paramsType = httpStatement.getParamsType();
        // 参数值
        Object[] paramsValues = SimpleTypeRegister.isSimpleType(paramsType) ? args.values().toArray() : new Object[]{args};
        logger.info("executor: {} methodName: {}, paramsType: {}, paramsValue: {}",
                this.getClass().getName(), httpStatement.getMethodName(), paramsType, paramsValues);
        try {
            Object result = this.doExecute(httpStatement.getMethodName(), new String[]{paramsType}, paramsValues);
            return SessionResult.success(result);
        } catch (Exception e) {
            logger.error("executor error", e);
            return SessionResult.fail(e.getMessage());
        }
    }

    protected abstract Object doExecute(String methodName, String[] paramsType, Object[] args);
}
